<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>vue3-to-wc</title>
  </head>
  <body>
    <!-- <script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script> -->
    <script src="libs/vue.global.prod.js"></script>
    <script src="dist/vue-web-components.umd.js"></script>

    <div>
      <button id="add">添加HelloWorld</button>
      <button id="modify">更改第一个helloworld的msg</button>
      <button id="remove">删除第一个HelloWorld</button>
    </div>
    <hello-world msg="Vue">
      <div style="color: chocolate; font-weight: bold">外部HTML内容</div>
    </hello-world>
    <script>
        const eventHandler = (e) => {
            alert(e.detail.msg);
        };

        VueWebComponents.registerWebComponents();

        const helloWorld = document.querySelector("hello-world");
        // 接收hello-world组件的广播的事件
        helloWorld.addEventListener("myEvent", eventHandler);

        // 添加
        const addButton = document.querySelector("#add");
        addButton.addEventListener("click", () => {
            const element = document.createElement("hello-world");
            const helloWorldNum = document.querySelectorAll("hello-world").length;
            element.setAttribute("msg", `Vue${helloWorldNum+1}`);
            document.body.appendChild(element);

            element.addEventListener("myEvent", eventHandler);
        });

        // 修改
        const modifyButton = document.querySelector("#modify");
        modifyButton.addEventListener("click", () => {
            const element = document.querySelector("hello-world");
            element.setAttribute("msg", "World");
        });

        // 删除
        const removeButton = document.querySelector("#remove");
        removeButton.addEventListener("click", () => {
            const element = document.querySelector("hello-world");
            element.remove();
            // 移除监听
            element.removeEventListener("myEvent", eventHandler);
        });
    </script>
  </body>
</html>
